var express = require('express');
var jwt = require('jsonwebtoken');
var nodemailer = require("nodemailer");
var constant = require('../../../private/constant');
var db = require('../../../tools/database')
var mail = require('../../../tools/mail')
var router = express.Router();
var util = require('../../../tools/util')

// 定义邮件服务器
var transporter = nodemailer.createTransport({
	host: constant.emailHost,
	service: constant.emailService,
	secure: true,
	auth: {
		user: constant.emailUser,
		pass: constant.emailSMTPSecret
	}
});

// 根据注册信息发送验证邮件
// 错误处理标准化 √√
router.use(function (req, res, next) {

	// 获取前端传递过来的参数
	let netID = req.body.netID;
	let userName = req.body.userName;
	let key = req.body.key;

	// 查询数据库 查看netID和用户名是否已经存在
	sql = `SELECT * FROM Users WHERE NetID=? OR UserName=?`;
	db.queryCallback(sql, [netID, userName], res, (result)=>{
		console.log(result);
		if (result !== undefined){
			util.errorRespond('USER_EXIST_ERROR', '', res)
		}else{
			// % 无重复用户，允许生成注册链接
			let token = jwt.sign({
				subject: 'register',
				issuer: 'Reina',
				netID: netID,
				userName: userName,
				key: key
			}, constant.secretKey, {
				// 过期时间:20分钟
				expiresIn: 1200
			});

			// 对token特殊处理, 以适应网址 (由于replace()只能替换一次，所以使用两次就没问题了)
			url_token = token.toString().replace(".", "@@").replace(".", "@@");
			let url = `${constant.host}/afterRegister?urlToken=${url_token}`;

			// 发送邮件
			sendRegisterMail(url, netID, res)
		}
	}, true, false)
});


function sendRegisterMail(url, netID, res){

	// 发送邮件
	var sendHtml = `<div><img src="https://s1.ax1x.com/2020/09/18/w4RjII.jpg" alt="w4RjII.jpg" /></div>
					<h4>最后一步！点击链接完成注册: <a href="${url}">验证链接</a></h4>`;

	var mailOptions = {
		// 发送邮件的地址
		from: 'reinaxxxxa@163.com',
		// 接收邮件的地址
		to: `${netID}@stu.xjtu.edu.cn`,
		// 邮件主题
		subject: '闲置公告板注册验证',
		// 以HTML的格式显示，这样可以显示图片、链接、字体颜色等信息
		html: sendHtml
	};
	mail.sendMail(mailOptions, (err) => {
		if (err){
			util.errorRespond('MAIL_SEND_ERROR', err, res)
		}else {
			util.dataRespond('', res)
		}
	})

}

module.exports = router;